<template>
  <div class="order-apply-invoice">
    <div ref="chartContainer" class="chart-container"></div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, onBeforeUnmount, watch, ref,nextTick } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  config: {
    type: Object,
    required: true,
    default: () => ({
      xAxisData: [],
      yAxisData: [],
      legendData:[]
    })
  }
})

const chartContainer = ref<HTMLElement | null>(null)
let chartInstance: echarts.ECharts | null = null

// 初始化图表
const initChart = () => {
  if (!chartContainer.value) return
  
  // 销毁现有实例
  if (chartInstance) {
    chartInstance.dispose()
  }
  
  // 创建新实例
  chartInstance = echarts.init(chartContainer.value)
  updateChart()
  
  // 初始渲染后立即调整大小
  chartInstance?.resize()
}

// 更新图表配置
const updateChart = () => {
  if (!chartInstance || !props.config) return

  const option = {
    legend: {
        right: '50px',
        top: '20px',
        data: [props.config.legendData[0] || '已提箱量']
    },
    grid: {
      left: '3%',
      right: '4%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: [...props.config.xAxisData],
      // axisLabel: {
      //   rotate: 30, // 标签旋转防止重叠
      //   interval: 0 // 强制显示所有标签
      // }
    },
    yAxis: {
      type: 'value',
      axisLine: { show: true },
      splitLine: { show: true }
    },
    series: [{
      name: props.config.legendData[0] || '已提箱量',
      data: [...props.config.yAxisData],
      type: 'line',
      smooth: true, // 平滑曲线
      symbol: 'circle', // 数据点形状
      symbolSize: 8, // 数据点大小
      itemStyle: {
        color: '#5470C6' // 线条颜色
      },
      lineStyle: {
        width: 3 // 线条宽度
      },
      areaStyle: { // 区域填充
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(84, 112, 198, 0.5)' },
          { offset: 1, color: 'rgba(84, 112, 198, 0.1)' }
        ])
      },
      label: {
          show: true, // 显示标签
          position: 'top',
          formatter: '{c}个', // 显示数据值
        }
    }],
    tooltip: { // 提示框配置
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    }
  }

  chartInstance.setOption(option)
}



onMounted(() => {
  nextTick(()=> { 
    initChart()
  })
})

onBeforeUnmount(() => {
  // 清理资源
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
})

// 监听配置变化
watch(() => props.config,() => {
    if (!chartInstance) {
      initChart()
    } else {
      updateChart()
    }
  },
  { deep: true, immediate: true }
)
</script>

<style lang="scss" scoped>
.order-apply-invoice {
  width: 100%;
  height: 100%;
  
  .chart-container {
    width: 100%;
    height: 100%;
    min-height: 400px; // 确保最小高度
  }
}
</style>